﻿using System;
using System.Linq;
using AccelerateSensor.Client.Forms;
using AccelerateSensor.Client.Tools;
using AccelerateSensor.Model.Node;
using AccelerateSensor.Service;
using ZbSkin.Tools;

namespace AccelerateSensor.Client.Controls
{
    public partial class NodeControl : PageControl
    {
        private string _gatewayUuid;

        public NodeControl()
        {
            InitializeComponent();
        }

        private void NodeControl_Load(object sender, EventArgs e)
        {
            DataGridViewHelper.SetCommonStyle(dataGridView);
            DataGridViewHelper.SetDatetimeStyle(dataGridView, "ColumnUpdateTime");
            dataGridView.ColumnHeadersVisible = true;
            ResizeControls();
        }

        private void NodeControl_Resize(object sender, EventArgs e)
        {
            ResizeControls();
        }

        private void ResizeControls()
        {
            SetRegion();

            dataGridView.Width = Width - 40;
            dataGridView.Height = Height - dataGridView.Top - btnDetail.Height * 2;
            btnDetail.Top = Height - (int)(btnDetail.Height * 1.5f);
            btnRealtimeData.Top = btnDetail.Top;
            btnHistoryData.Top = btnDetail.Top;
            btnGateway.Top = btnDetail.Top;
        }

        #region ShowControl/HideControl

        protected override void ShowControl(object data)
        {
            base.ShowControl(data);

            _gatewayUuid = (string) data;
            label_title.Text = $@"节点列表 - {_gatewayUuid}";

            UpdateDataGridView();
            RegisterServiceEvent();
        }

        protected override void HideControl()
        {
            dataGridView.DataSource = null;
            UnRegisterServiceEvent();
            base.HideControl();
        }

        private void RegisterServiceEvent()
        {
            AccelerateSensorService.Instance.NodeInfoChangedEvent += OnNodeInfoChanged;
            AccelerateSensorService.Instance.NodeDataChangedEvent += OnNodeDataChanged;
        }

        private void UnRegisterServiceEvent()
        {
            AccelerateSensorService.Instance.NodeInfoChangedEvent -= OnNodeInfoChanged;
            AccelerateSensorService.Instance.NodeDataChangedEvent -= OnNodeDataChanged;
        }

        #endregion

        private void OnNodeInfoChanged(NodeInfo nodeInfo)
        {
            var gatewayUuid = nodeInfo?.GatewayUuid;
            if (!string.IsNullOrWhiteSpace(gatewayUuid) && gatewayUuid.Equals(_gatewayUuid))
            {
                Context?.Post((state) => { UpdateDataGridView(); }, null);
            }
        }

        private void OnNodeDataChanged(NodeData nodeData)
        {
            var nodeList = AccelerateSensorService.Instance.GetNodeList(_gatewayUuid);
            if (nodeList.Count == 0)
            {
                var gatewayList = AccelerateSensorService.Instance.GatewayInfoList;
                nodeList = gatewayList.FirstOrDefault(t => _gatewayUuid.Equals(t.Uuid))?.NodeList;
            }

            var nodeInfo = nodeList?.FirstOrDefault(t => t.Uuid == nodeData?.NodeUuid);
            if (nodeInfo?.GatewayUuid == _gatewayUuid)
            {
                Context?.Post((state) => { UpdateDataGridView(); }, null);
            }
        }

        private void dataGridView_CellDoubleClick(object sender, System.Windows.Forms.DataGridViewCellEventArgs e)
        {
            ShowRealtimeData();
        }

        private void btnRealtimeData_Click(object sender, EventArgs e)
        {
            ShowRealtimeData();
        }

        private void btnHistoryData_Click(object sender, EventArgs e)
        {
            var info = dataGridView.CurrentRow?.DataBoundItem as NodeInfo;
            if (info == null)
            {
                return;
            }

            var tuple = new Tuple<string, string, int>(_gatewayUuid, info.Uuid, info.SleepTime);
            InvokeSwitchPage(new Tuple<string, object>(Constants.PageTag.NodeHistoryData, tuple));
        }

        private void btnGateway_Click(object sender, EventArgs e)
        {
            InvokeSwitchPage(new Tuple<string, object>(Constants.PageTag.Gateway, null));
        }

        private void UpdateDataGridView()
        {
            dataGridView.DataSource = null;

            if (string.IsNullOrWhiteSpace(_gatewayUuid))
            {
                return;
            }

            var nodeList = AccelerateSensorService.Instance.GetNodeList(_gatewayUuid);
            if (nodeList.Count == 0)
            {
                var gatewayList = AccelerateSensorService.Instance.GatewayInfoList;
                nodeList = gatewayList.FirstOrDefault(t => _gatewayUuid.Equals(t.Uuid))?.NodeList;
            }

            dataGridView.AutoGenerateColumns = false;
            dataGridView.DataSource = nodeList;
        }

        private void ShowRealtimeData()
        {
            var info = dataGridView.CurrentRow?.DataBoundItem as NodeInfo;
            if (info == null)
            {
                return;
            }

            UnRegisterServiceEvent();

            var form = new FrmNodeRealtimeData(_gatewayUuid, info.Uuid, info.SleepTime);
            form.ShowDialog(ParentForm);

            RegisterServiceEvent();
        }
    }
}
